/*
 * @Author: wuqingchun
 * @Date: 2024-10-21 13:50:31
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-10-31 20:44:43
 */
#ifndef __NET_TCP_SERVER_H__
#define __NET_TCP_SERVER_H__

#include <thread>
#include <netinet/in.h>

#include "libnet.h"

#include "net_tcp_connection.h"

#include "net_event_handler.h"
#include "net_connection_helper.h"

class CNetTCPServer : public INetTCPServer, public INetTCPConnectionCallback
{
public:
    CNetTCPServer(INetEventHandler& refEventHandler, INetTCPConnectionCallback& refCallback, const sockaddr_in& refAddr);
    ~CNetTCPServer();

    virtual int32_t Start();
    virtual void Stop();

    virtual void OnConnected(INetTCPConnection *pobjConn) override final;
    virtual void OnDisconnected(INetTCPConnection *pobjConn) override final;
    virtual void OnMessage(const void* pData, size_t ulDataLen) override final;
private:
    int32_t __CreateListener();
    ssize_t __RecvOne(int iFd, void* pBuf, size_t ulBufLen);
    void __Recv(int iFd);

    void __AddREvent(int iFd);
    void __DeleteREvent(int iFd);
    void __DealREvent(int iFd);

    void __AddWEvent(int iFd);
    void __DeleteWEvent(int iFd);
    void __DealWEvent(int iFd);

    int32_t __WaitEvent();

    void __ThreadFunc();
private:
    INetEventHandler& m_refEventHandler;
    INetTCPConnectionCallback& m_refCallback;
    sockaddr_in m_stAddr;

    int m_iListenSockFd = -1;

    fd_set m_stOriginReadSet;
    fd_set m_stOriginWriteSet;
    fd_set m_stTmpReadSet;
    fd_set m_stTmpWriteSet;

    int m_iMaxFd = -1;

    std::thread m_objThread;
    volatile bool m_bRunning = false;

    CNetConnectionListener* pobjListener = nullptr;
};

#endif //__NET_TCP_SERVER_H__